<?php

namespace App\Http\Controllers\BG;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

use \GatewayWorker\Lib\Gateway;

use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;

use  App\Models\SMS;

class SMSController extends Controller
{
    public function list(Request $request)
    {
        $input = Input::only('page','limit','start_at','end_at','str','is_send');
        $validator = Validator::make($input, [        
            'start_at' => 'nullable',
            'end_at' => 'nullable',
            'str' => 'nullable',
            'is_send' => 'nullable',
            'page' => 'required',
            'limit' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        // // msg_type
        $sms = SMS::leftJoin('t_phone', 't_phone.imei', '=', 't_sms.imei')->leftJoin('t_user', 't_user.id', '=', 't_phone.user_id');
        if(isset($input['start_at'])&&isset($input['end_at'])){
            $sms->whereBetween('sended_at',[$input['start_at'],$input['end_at']]);
        }
        if(isset($input['str'])){
            $sms->where('t_user.name','like' , '%'.$input['str'].'%')->orwhere('t_phone.imei','like' , '%'.$input['str'].'%');
        }
        if(isset($input['is_send'])){
            $sms->where('is_send',$input['is_send']);
        }
        $page = $input['page'];
        $limit = $input['limit'];
        $count =  $sms->count();
        $data = $sms
            ->select('t_sms.id','t_sms.is_send','t_sms.imei','t_sms.called_number','t_sms.content','t_sms.sended_at','t_user.name as phone_owner')
            ->offset(($page-1)*$limit)
            ->limit($limit)
            ->get();
        $fin['count'] = $count;
        $fin['data'] = $data;
        return $this->returnOk($fin);
    }

    public function delete(Request $request)
    {
        $input = Input::only('id');
        $validator = Validator::make($input, [   
            'id'      => 'required|string',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
       
        $where['id'] = $input['id'];
        $exist = SMS::where($where)->first();
        if($exist){
            $exist->delete();
        }else{
            return $this->returnError([],409,'信息不存在');
        }
        return $this->returnOk();
    }
}